package com.haoshuang.zhouzhoubang.ui.activity

import android.os.Bundle
import android.util.Log
import android.widget.RadioButton
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.ConvertUtils
import com.github.gzuliyujiang.wheelpicker.BirthdayPicker
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityPushOrder2Binding
import com.haoshuang.zhouzhoubang.model.bean.Cate
import com.haoshuang.zhouzhoubang.ui.adapter.ViewPagerAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.CustomPartShadowPopupView
import com.haoshuang.zhouzhoubang.ui.fragment.PushFragment
import com.haoshuang.zhouzhoubang.ui.vm.PushOrder2ViewModel
import com.haoshuang.zhouzhoubang.utils.TimeCallBack
import com.haoshuang.zhouzhoubang.utils.TimeCheckUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.formatMaxNum
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone
import java.util.*
import kotlin.collections.ArrayList


/**
 *  推送订单
 */
class PushOrder2Activity : BaseVMActivity<PushOrder2ViewModel, ActivityPushOrder2Binding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.clickWithTrigger { finish() }
        binding.appBar.tvTitle.text = "推送订单"


    }

    private val mFragments = ArrayList<Fragment>()  //存放学习子界面的Fragment集合

    val fm = PushFragment()
    val fm2 = PushFragment()
    val fm3 = PushFragment()
    var isRadioCheck = false //是否屏蔽radio改变的监听
    open var filter_type = 0
    open var start_date = ""
    open var type = 0
    open var end_date = ""
    open var cate_id = 0
    lateinit var currentRadio: RadioButton //当前的标签选项
    private fun getNet() {
        if (cate_id == 0) {
            if (filter_type == 3) {
                vm.getData(
                    "type" to 0,
                    "filter_type" to filter_type,
                    "start_date" to start_date,
                    "end_date" to end_date
                )
            } else {
                vm.getData(
                    "type" to 0, "filter_type" to filter_type
                )
            }

        } else {
            if (filter_type == 3) {
                vm.getData(
                    "type" to 0,
                    "filter_type" to filter_type,
                    "start_date" to start_date,
                    "end_date" to end_date,
                    "cate_id" to cate_id
                )
            } else {
                vm.getData(
                    "type" to 0,
                    "filter_type" to filter_type,
                    "cate_id" to cate_id
                )
            }
        }

    }

    override fun initData() {

        getNet()
        binding.apply {

            tvCustomTime2.clickWithTrigger {
                if (list22.size > 0) {
                    TimeCheckUtils.newInstance().Choose(
                        this@PushOrder2Activity, list22, tvCustomTime2,
                        TimeCallBack {
                            cate_id = list2[it.toInt()].id
                            getNet()
                            when (type) {
                                0 -> {
                                    fm.setNew()
                                }

                                1 -> {
                                    fm2.setNew()
                                }

                                2 -> {
                                    fm3.setNew()
                                }
                            }
                        }, "服务分类选择"
                    )
                } else {
                    toast("没有服务类别")
                }

            }
            radioGrop.setOnCheckedChangeListener { radioGroup, checkedId -> // 设置四个标签的选中事件改变时的监听
                /*由于点击自定义时间时会触发监听，因此在此处消耗一次需要*/
                if (isRadioCheck) {
                    isRadioCheck = false
                    return@setOnCheckedChangeListener
                } else {
                    currentRadio = radioGroup.findViewById<RadioButton>(checkedId)

                    llCustomTime.setBackgroundResource(R.drawable.recatangle_f5_12dp)
                    tvCustomTime.setTextColor(resources.getColor(R.color.c_66))


                    when (radioGroup.findViewById<RadioButton>(checkedId)) {
                        radioButton1 -> {
                            filter_type = 0
                        }

                        radioButton2 -> {
                            filter_type = 1
                        }

                        radioButton3 -> {
                            filter_type = 2
                        }

                    }
                    start_date = ""
                    end_date = ""
                    getNet()
                    when (type) {
                        0 -> {
                            fm.setNew()
                        }

                        1 -> {
                            fm2.setNew()
                        }

                        2 -> {
                            fm3.setNew()
                        }
                    }
                }
            }
            llCustomTime.clickWithTrigger {
                XPopup.Builder(this@PushOrder2Activity)
                    .atView(llLabRoot)
                    .isDestroyOnDismiss(false)
                    .setPopupCallback(object : SimpleCallback() {
                        override fun onCreated(popupView: BasePopupView?) {
                            super.onCreated(popupView)
                            // 弹窗内部onCreate执行完调用
                        }

                        override fun beforeShow(popupView: BasePopupView?) {
                            super.beforeShow(popupView)
                            //在每次show之前都会执行，可以用来进行多次的数据更新
                        }

                        override fun onShow(popupView: BasePopupView?) {
                            super.onShow(popupView)
                            // 完全显示的时候执行
                        }

                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            // 完全隐藏的时候执行
                        }

                        override fun beforeDismiss(popupView: BasePopupView?) {
                            super.beforeDismiss(popupView)
                            // 完全隐藏之前执行
                        }

                        //如果你自己想拦截返回按键事件，则重写这个方法，返回true即可
                        override fun onBackPressed(popupView: BasePopupView?): Boolean {
                            return super.onBackPressed(popupView)
                        }

                        //监听软键盘高度变化，高度为0说明软键盘关闭，反之则打开
                        override fun onKeyBoardStateChanged(
                            popupView: BasePopupView?,
                            height: Int
                        ) {
                            super.onKeyBoardStateChanged(popupView, height)
                        }

                        //监听弹窗拖拽，适用于能拖拽的弹窗
                        override fun onDrag(
                            popupView: BasePopupView?,
                            value: Int,
                            percent: Float,
                            upOrLeft: Boolean
                        ) {
                            super.onDrag(popupView, value, percent, upOrLeft)
                        }
                    })
                    .asCustom(
                        CustomPartShadowPopupView(
                            this@PushOrder2Activity,
                            ::creatTimePicker,
                            ::onCancel
                        ) { starTime, endTime ->
                            isRadioCheck = true
                            radioButton1.isChecked = false
                            radioButton2.isChecked = false
                            radioButton3.isChecked = false
                            isRadioCheck = false
                            llCustomTime.setBackgroundResource(R.drawable.recatangle_00b7f5_12dp)
                            tvCustomTime.setTextColor(resources.getColor(R.color.c_3b76c2))
                            filter_type = 3
                            start_date = starTime
                            end_date = endTime
                            getNet()
                            when (type) {
                                0 -> {
                                    fm.setNew()
                                }

                                1 -> {
                                    fm2.setNew()
                                }

                                2 -> {
                                    fm3.setNew()
                                }
                            }
                        }
                    )
                    .show()
            }
        }

        mFragments.add(fm)
        mFragments.add(fm2)
        mFragments.add(fm3)
        val mAdapter = ViewPagerAdapter(supportFragmentManager, lifecycle, mFragments)
        //  mAdapter = MyPagerAdapter2(parentFragmentManager,mFragments,mTitles88)
        binding.vpOrder.adapter = mAdapter
        binding.slidingTabLayout.setViewPager2(
            binding.vpOrder,
            arrayListOf("全部", "已接单", "未接单")
        )
        binding.vpOrder.offscreenPageLimit = 3

        binding.vpOrder.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                type = position

            }
        })
    }

    private fun onCancel() {

    }

    private fun creatTimePicker(it: TextView): String {
        var title = ""
        when (it.id) {
            R.id.tvStartTime -> {
                title = "开始时间"
            }

            R.id.tvEndTime -> {
                title = "结束时间"
            }
        }
        /*时间选择器需要用到的起止时间*/
        val calendar = Calendar.getInstance()
        var currentYear = calendar[Calendar.YEAR]
        var currentMonth = calendar[Calendar.MONTH] + 1
        var currentDay = calendar[Calendar.DAY_OF_MONTH]
        val startValue = DateEntity.target(currentYear - 100, 1, 1)
        val endValue = DateEntity.target(currentYear, currentMonth, currentDay)

        if (!it.text.isNullOrEmpty()) {
            val l = it.text.split("-")
            currentYear = l.get(0).toInt()
            currentMonth = l.get(1).toInt()
            currentDay = l.get(2).toInt()
        }

        val picker = BirthdayPicker(this@PushOrder2Activity)
        picker.setDefaultValue(currentYear, currentMonth, currentDay)   //设置默认值
        picker.wheelLayout.setRange(startValue, endValue)   // 设置起止时间
        picker.setTitle(title)   // 设置标题
        picker.setOnDatePickedListener { year, month, day ->
            (it as TextView).text = "$year-$month-$day"
        }
        picker.getWheelLayout().setResetWhenLinkage(false)
        picker.show()
        return "${(it as TextView).text}"
    }

    var demographicsList = arrayListOf<String>()
    var list2 = arrayListOf<Cate>()
    var list22 = arrayListOf<String>()
    override fun startObserve() {
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    binding.apply {
                        tvNum4.text = it.all_order_num.formatMaxNum(99)
                        tvNum5.text = it.take_order_num.formatMaxNum(99)
                        tvNum6.text = it.no_take_order_num.formatMaxNum(99)
                        tvNum4.visibleOrGone(it.all_order_num > 0)
                        tvNum5.visibleOrGone(it.take_order_num > 0)
                        tvNum6.visibleOrGone(it.no_take_order_num > 0)
                        demographicsList.clear()
                        demographicsList.add(it.push_notice)
                        list2.clear()
                        list22.clear()
                        list2.addAll(it.cate_list)
                        for (b in list2) {
                            list22.add(b.cate_name)
                        }
                        binding.scrollTextView.startWithList(demographicsList)
                    }
                }
            }
        }
    }

}